<template>
  <van-field
    v-model="fieldValue"
    :name="params.value"
    :label="params.label"
    :placeholder="params.placeholder || '请选择'"
    is-link
    v-bind="{ ...params.bind }"
    readonly
    @click="!params.refuseEvent && (showPicker = true)"
  />
  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
      :columns="params.options"
      v-bind="{ ...params.bind }"
      :columns-field-names="
        params.columnsFieldNames || {
          text: 'text',
          value: 'value',
          children: 'children',
        }
      "
      @confirm="getPickData"
      @cancel="showPicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import regexFunctions from '@/utils/regex.js'

const showPicker = ref(false)

// 校验并返回第一个错误
const validateByRegex = (input, regex) => {
  let flag = ''
  for (const element of regex) {
    if (!regexFunctions[element.regFun](input)) {
      flag = element.msg
      break
    }
  }
  return flag
}

const props = defineProps(['params', 'modelValue', 'formParams'])

const fieldValue = ref('')

const emits = defineEmits(['update:modelValue', 'validate', 'getText'])

const getPickData = data => {
  if (fieldValue.value && props.params.event) {
    props.params.event.funcName()
  }
  fieldValue.value =
    (data && data.selectedOptions[0].text) ||
    (props.modelValue &&
      props.params.options &&
      props.params.options.filter(item => item.value == props.modelValue)[0]
        .text)
  showPicker.value = false
  // change触发时 向父组件返回值 并将数据校验暴露出来
  data && emits('update:modelValue', data && data.selectedOptions[0].value)
  let key = `${props.params.value}_text`
  data && emits('getText', { [key]: data && data.selectedOptions[0].text })
  if (props.params.regex) {
    // 校验数据是否符合规则
    const res = validateByRegex(
      data && data.selectedOptions[0].value,
      props.params.regex,
    )
    emits('validate', {
      name: props.params.value,
      validateRes: res === '',
      validateMsg: res,
    })
  }
}

onMounted(() => {
  getPickData()
})
watch(
  () => props.modelValue,
  newVal => {
    props.params.options &&
      props.params.options.filter(item => item.value == newVal)[0] &&
      (fieldValue.value = props.params.options.filter(
        item => item.value === newVal,
      )[0].text)
    let key = `${props.params.value}_text`
    emits('getText', {
      [key]:
        props.params.options &&
        props.params.options.filter(item => item.value === newVal)[0] &&
        props.params.options.filter(item => item.value === newVal)[0].text,
    })
  },
)
</script>
